<template>
  <div class="charts" ref="chartsRef"></div>
  <div style="color: aliceblue; fontsize: 16px; display: inline-block"></div>
</template>

<script lang="ts">
export default {
  name: "PieChart",
};
</script>

<script lang="ts" setup>
import * as echarts from "echarts";
import { ref, watch } from "vue";
const chartsRef = ref();
const props = defineProps<{
  data: any;
  title: string;
}>();
watch(
  () => props.data,
  () => {
    const myEcharts = echarts.init(chartsRef.value);
    const data = (props.data.data1 as number[]).map((value, index) => {
      return {
        name: props.data.axisX[index] as string,
        value,
      };
    });
    // 计算总数
    const total = data.reduce((p, c) => p + c.value, 0);
    const option = {
      // 标题组件
      title: [
        {
          text: props.title, // 主标题
        },
        {
          text: "累计订单量", // 主标题
          subtext: total, // 副标题
          textStyle: {
            fontSize: 16, // //主标题文字字体大小
            color: "#rgb(153 150 153 / 1)",
            opacity: 0.6,
          },
          subtextStyle: {
            fontSize: 25, //副标题文字字体大小
            color: "#333",
          },
          left: "center",
          top: "42%",
        },
      ],
      // 提示框组件
      tooltip: {
        // 自定义提示内容
        formatter: function (params: any) {
          // console.log(params);
          const radius = `<div style="background-color:${params.color};border-radius: 50%; width: 10px; height: 10px;display: inline-block;"></div>`;
          const res = `${params.seriesName}<br/>${radius}  ${params.name}<br/>${radius}  数量: ${params.value}<br/>${radius}  百分比: ${params.percent}%`;
          return res;
        },
      },
      // 图例组件
      legend: {
        show: true,
        right: "10%",
        top: "middle",
        orient: "vertical", // 垂直布局
        textStyle: {
          color: "rgb(140 140 140)",
        },
        formatter: function (name: string) {
          const item = data.find((item) => item.name === name) as {
            name: string;
            value: number;
          };
          const percent = ((item.value / total) * 100).toFixed(2) + "%";
          return name + "|" + percent;
        },
      },
      series: [
        {
          name: props.title,
          type: "pie",
          data,
          // 半径:[内半径，外半径]
          radius: ["80", "110"],
          // 图形样式
          itemStyle: {
            borderWidth: 2, // 描边线宽
            borderColor: "#fff", // 图形的描边颜色
          },
        },
      ],
    };
    myEcharts.setOption(option);
  }
);
</script>

<style scoped>
.charts {
  width: 100%;
  height: 400px;
}
</style>
